<template>
    <div class="publish-channel-container">
        <a-row :style="{ marginBottom: '20px' }">
            <a-col :span="8" class="left-col">
                封面图
                <img :src="page.coverImg" :alt="page.title" />
            </a-col>
            <a-col :span="16" class="right-col">
                <a-row>
                    <a-col :span="6">
                        <img src="../../assets/logo.png" style="height: 40px;" />
                    </a-col>
                    <a-col :span="18" class="left-gap">
                        <h4>{{ page.title }}</h4>
                        <p>{{ page.desc }}</p>
                    </a-col>
                </a-row>

                <a-tabs type="card" :style="{ marginTop: '20px' }">
                    <a-tab-pane key="channels" tab="发布为作品">
                        <a-row v-for="channel in channels" :key="channel.id" class="channel-item">
                            <a-col :span="6">
                                <!-- 二维码 -->
                                <canvas :id="`channel-barcode-${channel.id}`" class="barcode-container"></canvas>
                            </a-col>
                            <a-col :span="18" class="left-gap">
                                <h4>{{ channel.name }}</h4>
                                <a-row>
                                    <a-col :span="16">
                                        <a-input :value="generateChannelURL(channel.id)" :readonly="true" :id="`channel-url-${channel.id}`"></a-input>
                                    </a-col>
                                    <a-col :span="3">
                                        <a-button class="copy-button" :data-clipboard-target="`#channel-url-${channel.id}`">复制</a-button>
                                    </a-col>
                                    <a-col :span="3">
                                        <a-button class="delete-button" type="primary"
                                            :style="{ marginLeft: '25px', backgroundColor: 'red' }"
                                            @click="deleteChannel(channel.id)" :disable="deleteDisabled">删除{{ channel.id
                                            }}</a-button>
                                    </a-col>
                                </a-row>

                            </a-col>
                        </a-row>
                        <a-form layout="inline" :style="{ marginTop: '20px' }" :model="form" :rules="rules">
                            <a-form-item name="channelName">
                                <a-input placeHolder="渠道名称" v-model:value="form.channelName"></a-input>
                            </a-form-item>
                            <a-form-item>
                                <a-button type="primary" @click="createChannel">创建新渠道</a-button>
                            </a-form-item>
                        </a-form>
                    </a-tab-pane>
                    <a-tab-pane key="templates" tab="发布为模板">
                    </a-tab-pane>
                </a-tabs>
            </a-col>


        </a-row>
    </div>
</template>

<script lang="ts" setup>
import { defineComponent, reactive, ref, Ref, computed, onMounted, watch, nextTick } from 'vue'
import { last } from 'lodash'
import { message } from 'ant-design-vue'
import { commonUploadCheck } from '@/helper'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { GlobalDataProps } from '@/store'
import { useForm } from 'ant-design-vue/es/form'
import {
    Tabs as aTabs,
    TabPane as aTabPane,
    Button as aButton,
    Form as aForm,
    FormItem as aFormItem,
    Input as aInput,
    Row as aRow,
    Col as aCol,
} from "ant-design-vue";
import { baseH5URL } from '@/main'
import QRCode from 'qrcode'
import ClipboardJS from 'clipboard'

const store = useStore<GlobalDataProps>()
const route = useRoute();
const currentWorkId = route.params.id as string
const page = computed(() => store.state.editor.page);
const channels = computed(() => store.state.editor.channels);

const form = reactive({
    channelName: ''
})
const rules = reactive({
    channelName: [
        { required: true, message: '标题不能为空', trigger: 'blur' },
    ]
})

const { validate } = useForm(form, rules);

const generateChannelURL = (id: number) => {
    return `${baseH5URL}/p/${page.value.id}-${page.value.uuid}?channel=${id}`
}

async function generateQRCode(id: string, url: string) {
    const canvas = document.getElementById(id) as HTMLCanvasElement
    console.log('canvas', id, canvas);
    if (!canvas) {
       await nextTick()
    }
    return QRCode.toCanvas(canvas, url, { width: 100 })
}

onMounted(() => {
    const clipboard = new ClipboardJS('.copy-button')
    clipboard.on('success', (e) => {
        message.success('复制成功')
        e.clearSelection()
    })
    // 生成二维码
    console.log( 'onMounted channels.value', channels.value);
    channels.value?.forEach(async (channel) => {
        try {
            await generateQRCode(`channel-barcode-${channel.id}`, generateChannelURL(channel.id))
        } catch (error) {
            console.error(error)
        }
    })
})

watch(channels, async (newChannels, oldChannels) => {
    // 生成二维码
    if( newChannels && oldChannels && newChannels.length > oldChannels.length) {
       const createChannel = last(newChannels);
       console.log('watch Channels', createChannel);
         if (createChannel) {
            // await nextTick()
            await generateQRCode(`channel-barcode-${createChannel.id}`, generateChannelURL(createChannel.id))
         }

    }
}, {flush: 'post', deep: true})  // 使用flush post 可以不要使用nextTick

const createChannel = async () => {
    const payload = {
        name: form.channelName,
        workId: parseInt(currentWorkId)
    }

    try {
        await validate();
        await store.dispatch('createChannel', { data: payload })
        form.channelName = ''
    } catch (error) {
        console.error(error)
    }
}

const deleteDisabled = computed(() => {
    return channels.value?.length === 1
})

const deleteChannel = async (channelId: string) => {
    try {
        // 转成string 
        const id = channelId.toString()
        await store.dispatch('deleteChannel', { urlParams: { id: id } })
    } catch (error) {
        console.error(error)
    }
}




</script>

<style scoped></style>